package com.jason.canvaslayer.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.View;

import com.jason.canvaslayer.R;

/**
 *
 * canvas中变换操作: 平移 translate(float dx, float dy)
 *                  旋转 rotate
 *                  缩放 scale(float sx, float sy, float px, float py)
 *                       后两个参数用于指定缩放中心点  前两个参数用于指定横纵向的缩放比率值在0-1之间为缩小
 *                  错切 skew
 *
 *
 * @DESC:   canvas的缩放
 * @Author: Jason
 * @Date: 16/9/26
 * @Time: 16:40
 */

public class CanvasScaleView5 extends View {

    private Bitmap mBitmap; // 位图对象
    private int mViewWidth, mViewHeight;

    public CanvasScaleView5(Context context, AttributeSet attrs) {
        super(context, attrs);

        // 获取位图对象
        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.z);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        // 获取控件宽高
        mViewWidth = w;
        mViewHeight = h;

        // 缩放位图与控件一致
        mBitmap = Bitmap.createScaledBitmap(mBitmap, mViewWidth, mViewHeight, true);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        //canvas.scale(1.0F, 1.0F); // 缩放比例为1时表示不缩放
        //canvas.scale(0.8F, 0.35F);
        // 更改缩放中心
        //canvas.scale(0.8F, 0.35F, mViewWidth, 0);

        // 错切
        //canvas.skew(0.5F, 0F); // 两个参数与scale类似 表示横纵向的错切比率

        // canvas也提供了对应的方法设置Matrix直接变换Canvas
        Matrix matrix = new Matrix();
        matrix.setScale(0.8F, 0.35F);
        matrix.postTranslate(100, 100);
        canvas.setMatrix(matrix);

        canvas.drawBitmap(mBitmap, 0, 0, null);
        canvas.restore();

    }
}
